package com.agent.user.service;

import com.agent.common.exception.BusinessException;
import com.agent.common.result.PageResult;
import com.agent.common.result.ResultCode;
import com.agent.common.utils.IdGenerator;
import com.agent.user.dto.KeywordPage;
import com.agent.user.entity.AdminUser;
import com.agent.user.mapper.AdminUserMapper;
import com.agent.user.utils.PasswordUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.ZoneOffset;

@Service
@RequiredArgsConstructor
public class AdminUserService {
    private final AdminUserMapper adminUserMapper;
    private final IdGenerator idGenerator = IdGenerator.getInstance();

    @Transactional
    public AdminUser createAdmin(AdminUser adminUser) {
        // 检查用户名是否已存在
        AdminUser existing = adminUserMapper.selectOne(new QueryWrapper<AdminUser>()
                .eq("username", adminUser.getUsername()));
        if (existing != null) {
            throw new BusinessException(ResultCode.ADMIN_USER_ALREADY_EXISTS);
        }

        // 设置ID和创建时间
        adminUser.setId(idGenerator.nextId());
        adminUser.setCreatedAt(LocalDateTime.now(ZoneOffset.UTC));
        adminUser.setUpdatedAt(LocalDateTime.now(ZoneOffset.UTC));

        // 加密密码
        adminUser.setPassword(PasswordUtils.encode(adminUser.getPassword()));

        // 设置默认状态
        if (adminUser.getStatus() == null) {
            adminUser.setStatus(1); // 默认启用
        }

        adminUserMapper.insert(adminUser);
        return adminUser;
    }

    @Transactional
    public AdminUser updateAdmin(AdminUser updateRequest) {
        AdminUser admin = adminUserMapper.selectById(updateRequest.getId());
        if (admin == null) {
            throw new BusinessException(ResultCode.USER_NOT_EXIST, "Admin not found");
        }

        // 更新基本信息
        if (updateRequest.getEmail() != null) {
            admin.setEmail(updateRequest.getEmail());
        }

        // 更新密码
        if (updateRequest.getPassword() != null) {
            admin.setPassword(PasswordUtils.encode(updateRequest.getPassword()));
        }

        // 更新状态
        if (updateRequest.getStatus() != null) {
            admin.setStatus(updateRequest.getStatus());
        }

        admin.setUpdatedAt(LocalDateTime.now(ZoneOffset.UTC));
        adminUserMapper.updateById(admin);
        return admin;
    }

    @Transactional
    public void deleteAdmin(Long id) {
        int result = adminUserMapper.deleteById(id);
        if (result == 0) {
            throw new BusinessException(ResultCode.USER_NOT_EXIST, "Admin not found");
        }
    }

    public AdminUser getAdminById(Long id) {
        AdminUser admin = adminUserMapper.selectById(id);
        if (admin == null) {
            throw new BusinessException(ResultCode.USER_NOT_EXIST, "Admin not found");
        }
        return admin;
    }

    public IPage<AdminUser> searchAdmins(KeywordPage page) {
        Page<AdminUser> pageParam = new Page<>(page.getPage(), page.getSize());
        return adminUserMapper.searchAdmins(pageParam, page.getKeyword());
    }
}